package top.scauwlt.remoting.transport.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.scauwlt.config.RpcConfig;
import top.scauwlt.enums.CompressTypeEnum;
import top.scauwlt.enums.SerializationTypeEnum;
import top.scauwlt.extension.ExtensionLoader;
import top.scauwlt.factory.SingletonFactory;
import top.scauwlt.registry.ServiceDiscovery;
import top.scauwlt.remoting.constants.RpcConstants;
import top.scauwlt.remoting.dto.RpcMessage;
import top.scauwlt.remoting.dto.RpcRequest;
import top.scauwlt.remoting.transport.codec.RpcMessageDecoder;
import top.scauwlt.remoting.transport.codec.RpcMessageEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author wmm
 * @Date 2022/7/26 23:02
 */
@Slf4j
public class NettyRpcClient {
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;
    private final ChannelProvider channelProvider;
    private final ServiceDiscovery serviceDiscovery;
    private final UnprocessedRequests unprocessedRequests;

    public NettyRpcClient() {
        bootstrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                //连接超时时间
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        // 5s内未发送数据，则发一次心跳
                        pipeline.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS))
                                .addLast(new RpcMessageEncoder())
                                .addLast(new RpcMessageDecoder())
                                .addLast(new NettyRpcClientHandler());
                    }
                });
        channelProvider = SingletonFactory.getInstance(ChannelProvider.class);
        serviceDiscovery = ExtensionLoader.getExtensionLoader(ServiceDiscovery.class).getExtension(RpcConfig.getInstance().getRegistryType());
        unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
    }

    @SneakyThrows
    private Channel doConnect(InetSocketAddress inetSocketAddress) {
        CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
        bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("The client has connected [{}] successful!", inetSocketAddress.toString());
                Channel channel = future.channel();
                completableFuture.complete(channel);
            } else {
                throw new IllegalStateException("Client connect fail : [{}] " + inetSocketAddress.toString());
            }
        });
        return completableFuture.get();
    }

    /**
     * 发送请求的流程
     * 1.使用ServiceDiscovery发现服务地址
     * 2.建立连接，根据请求创建请求消息
     * 3.把该异步任务对象放入UnprocessedMap，key是生成的UUID请求ID
     * 4.返回该异步任务，当接收到服务端发回的响应时结束异步任务
     *
     * @param rpcRequest
     * @return
     */
    public Object sendRequest(RpcRequest rpcRequest) {
        CompletableFuture resultFuture = new CompletableFuture();
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest);
        Channel channel = getChannel(inetSocketAddress);
        if (channel.isActive()) {
            unprocessedRequests.put(rpcRequest.getRequestId(), resultFuture);
            RpcMessage rpcMessage = RpcMessage.builder()
                    .messageType(RpcConstants.REQUEST_TYPE)
                    .codec(SerializationTypeEnum.getCode(RpcConfig.getInstance().getSerializationType()))
                    .compress(CompressTypeEnum.getCode(RpcConfig.getInstance().getCompressType()))
                    .data(rpcRequest).build();
            channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("client send request : [{}] successfully!", rpcMessage);
                } else {
                    future.channel().close();
                    resultFuture.completeExceptionally(future.cause());
                    log.error("client send message failed: ", future.cause());
                }
            });
        } else {
            throw new IllegalStateException();
        }
        return resultFuture;
    }

    public Channel getChannel(InetSocketAddress inetSocketAddress) {
        Channel channel = channelProvider.get(inetSocketAddress);
        if (channel == null) {
            channel = doConnect(inetSocketAddress);
            channelProvider.set(inetSocketAddress, channel);
        }
        return channel;
    }

}
